from typing import Optional, List
from pydantic import BaseModel, Field, validator
from app.schemas.account import PaginationMeta, PaginationLinks, PaginationMetaWrapper
import re


class RuleBase(BaseModel):
    account_id: str = Field(..., description="账套ID")
    ccode: str = Field(..., description="科目编码")
    ass: str = Field(..., description="辅助账类型",)  # C=客户, V=供应商, P=个人
    name: str = Field(..., description="科目名称")
    classification: str = Field(..., description="重分类科目名称")
    direction: str = Field(..., description="余额方向")
    status: int = Field(1, description="状态")
    
    @validator('ccode')
    def validate_ccode(cls, v):
        if not re.match(r'^\d+$', v):
            raise ValueError('科目编码只能包含数字')
        return v


class RuleCreate(RuleBase):
    pass


class RuleUpdate(BaseModel):
    ccode: Optional[str] = Field(None, description="科目编码")
    ass: Optional[str] = Field(None, description="辅助账类型")
    name: Optional[str] = Field(None, description="科目名称")
    classification: Optional[str] = Field(None, description="重分类科目名称")
    direction: Optional[str] = Field(None, description="余额方向")
    status: Optional[int] = Field(None, description="状态")
    
    @validator('ccode')
    def validate_ccode(cls, v):
        if v is not None and not re.match(r'^\d+$', v):
            raise ValueError('科目编码只能包含数字')
        return v


class Rule(RuleBase):
    id: str
    create_time: int
    update_time: int
    create_user_id: str
    update_user_id: str

    class Config:
        orm_mode = True
        from_attributes = True


class RuleListResponse(BaseModel):
    data: List[Rule] = Field(..., description="分类规则列表")
    meta: PaginationMetaWrapper = Field(..., description="分页元信息")
    links: PaginationLinks = Field(..., description="分页链接")